package com.hibernate.hrm.config.login;

import com.hibernate.hrm.entity.User;
import com.hibernate.hrm.service.login.OperateLogService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomLogoutHandler implements LogoutHandler {

    private final OperateLogService operateLogService;
    private final HttpServletRequest request;

    public CustomLogoutHandler(OperateLogService operateLogService,
                               HttpServletRequest request) {
        this.operateLogService = operateLogService;
        this.request = request;
    }

    @Override
    public void logout(HttpServletRequest request,
                       HttpServletResponse response,
                       Authentication authentication) {
        if (authentication != null && authentication.getPrincipal() instanceof User) {
            User user = (User) authentication.getPrincipal();
            operateLogService.recordLogoutLog(user.getUserId(), request);
        }
    }
}
